package com.xuecheng.content.config;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.io.IoUtil;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import io.minio.*;
import io.minio.errors.*;
import io.minio.messages.Item;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import javax.annotation.PostConstruct;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

/**
 * @author HuangYuwu
 * @CreateTime 2022/9/11 18:48
 */
@Component
@Slf4j
public class MinioTemplate {

    @Autowired
    private MinioProperties minioProp;

    private MinioClient minioClient;

    //初始化
    @PostConstruct
    public void init() {
        minioClient = MinioClient.builder()
                .credentials(minioProp.getAccesskey(), minioProp.getSecretKey())
                .endpoint(minioProp.getEndpoint()).build();
    }

    /**
     * 上传图片到Minio
     *
     * @param inputStream
     * @param filename
     * @param contentType
     * @return
     */
    public String upload(InputStream inputStream, String filename, String contentType) {
        try {
            //文件上传路径
            String filePath = "images/" + DateTime.now().toString("yyyy/MM/dd/")
                    + UUID.randomUUID().toString() + filename;
            //构建参数
            PutObjectArgs args = PutObjectArgs.builder()
                    .bucket(minioProp.getBucket())
                    .object(filePath)
                    .contentType(contentType)
                    .stream(inputStream, inputStream.available(), -1)
                    .build();
            //上传文件
            minioClient.putObject(args);
            //图片访问路径
            String imageUrl = minioProp.getDomain() + "/" + minioProp.getBucket() + "/" + filePath;
            return imageUrl;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 上传html文件到Minio
     *
     * @param inputStream
     * @param filename
     * @return
     */
    public String uploadHtml(InputStream inputStream, String filename) {
        try {
            //文件上传路径
            String filePath = "pages/" + filename;
            //构建参数
            PutObjectArgs args = PutObjectArgs.builder()
                    .bucket(minioProp.getBucket())
                    .object(filePath)
                    .contentType("text/html")
                    .stream(inputStream, inputStream.available(), -1)
                    .build();
            //上传文件
            minioClient.putObject(args);
            //访问路径
            String htmlUrl = minioProp.getDomain() + "/" + minioProp.getBucket() + "/" + filePath;
            return htmlUrl;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Async
    public void deleteImage(String imageUrl) throws ServerException, InvalidBucketNameException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {

        String[] split = imageUrl.split(minioProp.getDomain() + "/" + minioProp.getBucket());
        String objectName = split[split.length - 1];
        //使用MinIO服务器、其访问密钥和密钥创建minioClient
        MinioClient minioClient = MinioClient.builder()
                //MinIO服务器访问网址端口
                .endpoint(minioProp.getEndpoint())
                //MinIO服务器登录账号和密码
                .credentials(minioProp.getAccesskey(), minioProp.getSecretKey())
                .build();
        minioClient.removeObject(RemoveObjectArgs.builder()
                .bucket(minioProp.getBucket())
                .object(objectName)
                .build());

    }

    public void deleteHtml(String objectName) throws ServerException, InvalidBucketNameException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {

        //使用MinIO服务器、其访问密钥和密钥创建minioClient
        MinioClient minioClient = MinioClient.builder()
                //MinIO服务器访问网址端口
                .endpoint(minioProp.getEndpoint())
                //MinIO服务器登录账号和密码
                .credentials(minioProp.getAccesskey(), minioProp.getSecretKey())
                .build();
        minioClient.removeObject(RemoveObjectArgs.builder()
                .bucket(minioProp.getBucket())
                .object(objectName)
                .build());

    }
}
